<script setup lang="ts">
import { onMounted, ref } from 'vue';
import AddStudent from './AddStudent.vue';
import { getUserList,removeUser } from '@/api/classroom';
import { showConfirmDialog, showToast } from 'vant';

const props = defineProps<{ courseId: string }>();
const studentList = ref<any[]>([]);

const showAddStudent = ref(false);
const isManage = ref(false);  

const fetchStudentList = async () => {
  const res = await getUserList(props.courseId,2);
  studentList.value = res.data || [];
};

const handleRemove = async (studentId: string) => {
  try {
    await showConfirmDialog({
      message: '确认要将该学生移出班级吗？'
    });
    await removeUser(props.courseId, studentId);
    showToast('移除成功');
    fetchStudentList(); // 刷新
  } catch (err) {
    console.log(err);
    showToast('取消或失败');
  }
};
onMounted(() => {
  fetchStudentList();
});
</script>

<template>
    <div class="student-list">
      <!-- 已有学生列表 -->
       <!-- 管理按钮 -->
    <div class="student-list-header">    
    <van-button 
    size="small" 
   @click="isManage = !isManage">
      {{ isManage ? '取消管理' : '管理学生' }}
    </van-button>
  </div>
      <van-cell
        v-for="student in studentList"
        :key="student.id"
        :title="student.nickname"
        :label="student.studentId"
      >
        <template #icon>
          <van-image width="50" height="50" :src="student.avatar" fit="cover" round />
        </template>
        <template #extra v-if="isManage">
        <van-button size="small" type="danger" @click="handleRemove(student.id)">移除</van-button>
      </template>
      </van-cell>
      <van-button type="primary" block @click="showAddStudent = true">
      添加学生
    </van-button>
    <!-- 添加学生弹窗 -->
    <AddStudent
      v-model:show="showAddStudent"
      :courseId="props.courseId"
      @refreshStudentList="fetchStudentList"
    />
    </div>
  </template>

<style lang="scss" scoped>
.student-list-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.manage-btn {
  background-color: transparent;
  border: none;
  color: #1989fa;
  font-size: 14px;
  padding: 0;
  box-shadow: none;
}

.manage-btn:hover {
  opacity: 0.8;
}

.van-cell {
  margin-bottom: 10px;
}

.van-image {
  margin-right: 10px;
}

.add-student-container {
  margin-top: 20px;
  padding: 0 10px;
}
</style>
